import { useEffect, useRef, useState } from "react";
import "./App.css";

function App() {
   const [count, setCount] = useState(0)

   const updateCount = () => {
    setCount(count + 1)
   }

   const ref = useRef(updateCount)
   ref.current = updateCount

   useEffect(() => {
    // 这样会跑很多次定时器
    console.log(count, 'count');
    // 通过‘useRef’保存最新的函数；而ref.current每次渲染都会更新，保存最新的值
    // ref.current的改变不会触发重新渲染
    const timer = setInterval(() => ref.current(), 1000)
    return () => {
        clearInterval(timer)
    }
   }, [])

   return <>
    <div>{count}</div>
   </>
}

export default App;
